<template>
	<div class="main">
		<cl-crud @load="onLoad">
			<template #slot-filter>
				<div class="nav base-flex" style="margin-right:10px">
					<div class="time">
						<el-date-picker
							type="datetimerange"
							size="mini"
							value-format="yyyy-MM-dd HH:mm:ss"
							v-model="timepicker"
							@change="
								val =>
									crud.refresh({
										startTime: val ? val[0] : '',
										endTime: val ? val[1] : '',
										page: 1
									})
							"
							@refresh="crud.refresh({ startTime: '', endTime: '', page: 1 })"
						></el-date-picker>
					</div>
					<div class="nav-li">
						商品状态
						<el-select
							size="mini"
							v-model="status"
							@change="val => crud.refresh({ status: val, page: 1 })"
						>
							<el-option label="全部" value></el-option>
							<el-option label="上架" :value="1"></el-option>
							<el-option label="已下架" :value="2"></el-option>
						</el-select>
					</div>
				</div>
			</template>
			<template #table-column-goodInfo="{scope}">
				<good-info :item="scope.row"></good-info>
			</template>
			<template #table-column-couponInfo="{scope}">
				<coupon-info :item="scope.row"></coupon-info>
			</template>
			<template #table-column-isDHh="{scope}">
				<div>
					<el-tag v-if="scope.row.isDHh == 1" type="success">是</el-tag>
					<el-tag type="info" v-else>否</el-tag>
				</div>
			</template>
			<template #table-column-isNine="{scope}">
				<div>
					<el-tag v-if="scope.row.isNine == 1" type="success">是</el-tag>
					<el-tag type="info" v-else>否</el-tag>
				</div>
			</template>
			<template #table-column-platform="{scope}">{{
				scope.row.source | dict_platform
			}}</template>
			<template #slot-setTime>
				<el-button size="mini" @click="setTime()">抢购时间管理</el-button>
			</template>
			<template #table-column-count="{scope}">
				<div style="text-align:left">
					<div>
						免单金额：
						<span style="color:red">{{ scope.row.tljMoney }}</span>
					</div>
					<div>
						总数：
						<span style="color:red">{{ scope.row.total }}</span>
					</div>
					<div>
						已领数量：
						<span style="color:red">{{ scope.row.receiveNum }}</span>
					</div>
					<div>
						剩余数量：
						<span style="color:red">{{ scope.row.surplus }}</span>
					</div>
					<div>
						预设数量：
						<span style="color:red">{{ scope.row.defNum }}</span>
					</div>
					<!-- <div>
						淘礼金数量：<span style="color:red">{{ scope.row.defNum }}</span>
					</div>
					<div>
						淘礼金金额：<span style="color:red">{{ scope.row.defNum }}</span>
					</div>-->
				</div>
			</template>
			<template #table-column-startTime="{scope}">
				<div>活动开始时间：{{ scope.row.startTime | dateFormatLine }}</div>
				<div>活动结束时间：{{ scope.row.endTime | dateFormatLine }}</div>
			</template>
			<template #table-column-tlj="{scope}">
				<div>
					淘礼金金额：
					<span style="color:red">{{ scope.row.tljMoney }}</span>
				</div>
			</template>
			<template #slot-setSort="{scope}">
				<span class="setsort" @click="setGoodsort(scope.row)">修改</span>
			</template>
			<template #slot-catGoodsinfo="{scope}">
				<el-button type="text" @click="catGoodsInfo(scope.row)">查看抢购详情</el-button>
			</template>
			<template #table-column-status="{scope}">
				<div>
					<el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
					<el-tag type="info" v-if="scope.row.status == 2">已下架</el-tag>
				</div>
			</template>
		</cl-crud>

		<cl-form ref="cl-form">
			<template #slot-setTime="{scope}">
				<div>
					<setTime @input="val => (scope.timer = val)"></setTime>
				</div>
			</template>
		</cl-form>
	</div>
</template>

<script>
import goodInfo from '../components/list/good-info';
import couponInfo from '../components/list/coupon-info';
import searchCounpon from './components/searchGoods';
import setTime from '../components/setTime';
import moment from 'moment';
import stores from '@/utils/store';
import _ from 'lodash';

export default {
	data() {
		return {
			activityTime: 1,
			crud: null,
			enterGoodsInfo: {},
			setTimeList: [],
			status: 1,
			params: {
				prop: 'createTime',
				order: 'desc',
				status: 1,
				startTime: moment().format('YYYY-MM-DD 00:00:00'),
				endTime: moment().format('YYYY-MM-DD 23:59:59'),
				type: 1
			},
			timepicker: [
				moment().format('YYYY-MM-DD 00:00:00'),
				moment().format('YYYY-MM-DD 23:59:59')
			],
			defNumMax: 1,
			formList: [], // 平台列表
			appName: '',
			selects: {
				app: []
			},
			enterGoodsInfo: {} //添加时 检测出的商品信息
		};
	},
	components: {
		goodInfo,
		couponInfo,
		// eslint-disable-next-line
		searchCounpon,
		setTime
	},
	created() {
		this.$service.common.userAppList().then(res => {
			let list = res.map(el => {
				return {
					label: el.name,
					value: el.key
				};
			});
			this.formList = list;
		});
	},
	methods: {
		catGoodsInfo(item) {
			this.$emit('showdetail', item);
		},

		setTime() {
			const self = this;
			this.$refs['cl-form'].open({
				props: {
					'label-width': '0',
					width: '800px',
					center: true,
					'custom-class': 'custom-class-dialog-mini'
				},
				items: [
					{
						prop: 'timer',
						component: {
							name: 'slot-setTime'
						}
					}
				],
				on: {
					submit({ data, close }) {
						self.$service.goodsMenagement.goods
							.addFlashTime({
								time: data.timer.join(',')
							})
							.then(() => {
								self.$message({
									message: '设置成功',
									type: 'success'
								});
								self.crud.refresh();
								close();
								return;
							})
							.catch(err => {
								self.$message.error(err);
							});
					}
				}
			});
		},
		async setGoodsort(item) {
			const self = this;

			this.defNumMax = item.total;
			let independentSort = await this.$service.goodsMenagement.mdGoods.independentSort({
				id: item.id
			});
			let appArr = [];
			independentSort.map(i => {
				appArr.push(i.app);
			});

			this.$refs['cl-form'].open({
				props: {
					'label-width': '90px',
					center: true,
					'custom-class': 'custom-class-dialog-mini'
				},
				items: [
					{
						prop: 'pic',
						label: '商品主图：',
						span: 24,
						value: item.pic,
						component: {
							name: 'cl-upload'
						}
					},
					{
						prop: 'title',
						label: '商品标题',
						span: 24,
						value: item.title,
						component: {
							name: 'el-input',
							attrs: {
								size: 'mini'
							}
						}
					},
					{
						prop: 'ysqLevel',
						label: '排序值',
						span: 24,
						value: item.ysqLevel ? item.ysqLevel : 100,
						component: {
							name: 'ysqlevel-input',
							data() {
								return {
									value2: 0
								};
							},
							props: {
								value: [String, Number]
							},
							mounted() {
								this.value2 = this.value;
							},
							methods: {
								input(e) {
									this.$emit('input', e);
								}
							},
							render() {
								return (
									<div style="display:flex">
										<el-input-number
											controls-position="right"
											min={1}
											max={100000}
											onInput={this.input}
											v-model={this.value2}></el-input-number>
										<span style="color:red;margin-left:10px">
											* 序号越大，排序越靠前
										</span>
									</div>
								);
							}
						},
						rules: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
					},
					{
						prop: 'total',
						label: '免单总数',
						span: 24,
						value: item.total,
						component: {
							name: 'total-input',
							data() {
								return {
									value2: 0
								};
							},
							attrs: {
								surplus: item.surplus,
								total: item.total
							},
							props: {
								value: [String, Number]
							},
							mounted() {
								this.value2 = this.value;
							},
							methods: {
								input(e) {
									this.$emit('input', e);
								}
							},
							render() {
								return (
									<div style="display:flex">
										<el-input-number
											controls-position="right"
											min={this.$attrs.surplus}
											max={100000}
											onInput={this.input}
											v-model={this.value2}></el-input-number>
										<span style="color:red;margin-left:10px">
											* 剩余数量{' '}
											{this.$attrs.surplus +
												(this.value2 - this.$attrs.total)}
										</span>
									</div>
								);
							}
						},
						rules: [{ required: true, message: '免单总数不能为空', trigger: 'blur' }]
					},
					{
						prop: 'tljMoney',
						label: '免单金额',
						value: item.tljMoney,
						span: 15,
						component: {
							name: 'el-input-number',
							props: {
								min: 0,
								max: 100000
							},
							on: {
								change(val) {
									self.defNumMax = val;
								}
							}
						},
						rules: [{ required: true, message: '免单金额不能为空', trigger: 'blur' }]
					},
					{
						prop: 'defNum',
						label: '预设抢购',
						value: item.defNum || '',
						component: {
							name: 'defNum-s',
							data() {
								return {
									value2: 0
								};
							},
							props: {
								value: [String, Number]
							},
							mounted() {
								this.value2 = this.value;
							},
							methods: {
								input(e) {
									this.$emit('input', e);
								}
							},
							render() {
								return (
									<div>
										<el-input-number
											v-model={this.value2}
											controls-position="right"
											onInput={this.input}
											min={0}
											max={self.defNumMax}></el-input-number>
									</div>
								);
							}
						}
					},
					{
						prop: 'appSort',
						label: '显示平台',
						value: appArr,
						component: {
							name: 'slelect-app2',
							data() {
								return {
									list: [],
									checked: false
								};
							},
							props: {
								value: null
							},
							watch: {
								value: {
									immediate: true,
									handler(val) {
										this.list = val;
									}
								}
							},
							methods: {
								change(e) {
									this.$emit('input', e);
								},
								changeAll(type) {
									let all = [];
									self.formList.map(i => {
										all.push(i.value);
									});
									if (type) {
										this.list = all;
									} else {
										this.list = [];
									}
									this.$emit('input', this.list);
								}
							},
							render() {
								return (
									<div>
										<el-select
											clearable
											multiple
											style="width:100%"
											onChange={this.change}
											v-model={this.list}
											placeholder="请选择">
											{self.formList.map(e => {
												return (
													<el-option
														key={e.key}
														label={e.label}
														value={e.value}></el-option>
												);
											})}
										</el-select>
										<el-checkbox
											v-model={this.checked}
											onChange={this.changeAll}>
											全选平台
										</el-checkbox>
									</div>
								);
							}
						}
					},
					{
						label: '状态',
						prop: 'status',
						value: 1,
						component: {
							name: 'el-radio-group',
							options: [
								{
									label: '上架',
									value: 1
								},
								{
									label: '下架',
									value: 2
								}
							]
						}
					}
				],
				on: {
					submit({ data, close }) {
						let aList = [];
						let d = _.cloneDeep(data.appSort);
						d.map(i => {
							aList.push({
								title: '',
								pick: '',
								level: '0',
								label: '',
								app: i
							});
						});
						self.$service.goodsMenagement.mdGoods
							.updateInfo({
								...data,
								appSort: aList,
								id: item.id,
								mdId: item.mdId,
								surplus: data.total - item.receiveNum,
								gid: item.gid
							})
							.then(() => {
								self.$message({
									message: '设置成功',
									type: 'success'
								});
								self.crud.refresh();
								close();
								return;
							})
							.catch(err => {
								self.$message.error(err);
							});
					}
				}
			});
		},
		onLoad({ ctx, app }) {
			const self = this;
			this.crud = app;

			ctx.service(this.$service.goodsMenagement.mdGoods)
				.set('dict', {
					label: {
						add: '添加抢购商品'
					},
					api: {
						update: 'updateInfo'
					}
				})
				.set('table', {
					columns: [
						{
							label: '序号',
							type: 'index',
							align: 'center',
							width: 80
						},
						{
							label: '商品信息',
							prop: 'goodInfo',
							align: 'left',
							'min-width': 400
						},
						{
							label: '优惠券信息',
							prop: 'couponInfo',
							align: 'left',
							'min-width': 350
						},
						{
							label: '月销量',
							prop: 'sale',
							align: 'center'
						},
						{
							label: '商品排序',
							prop: 'ysqLevel',
							align: 'center',
							sortable: 'custom',
							emptyText: '0',
							'min-width': 100
						},
						{
							label: '数据统计',
							prop: 'count',
							align: 'center',
							sortable: 'custom',
							'min-width': '130px'
						},
						{
							label: '活动时间',
							prop: 'startTime',
							align: 'center',
							sortable: 'custom',
							'min-width': '250px'
						},
						{
							label: '淘礼金',
							prop: 'tlj',
							align: 'center',
							sortable: 'custom',
							'min-width': '250px'
						},
						{
							label: '佣金比例',
							prop: 'commissionRate',
							align: 'center'
						},
						{
							label: '9.9包邮',
							prop: 'isNine',
							align: 'center'
						},
						{
							label: '抖好货',
							prop: 'isDHh',
							align: 'center'
						},
						{
							label: '商品状态',
							prop: 'status',
							align: 'center',
							'min-width': 100
						},
						{
							label: '平台',
							prop: 'platform',
							align: 'center'
						}
					],

					op: {
						visible: true,
						layout: ['slot-setSort', 'slot-delete', 'slot-catGoodsinfo']
					}
				})
				.set('upsert', {
					props: {
						labelWidth: '120px',
						center: true,
						'custom-class': 'custom-class-dialog'
					},
					items: [
						{
							prop: 'pic',
							label: '商品主图：',
							span: 24,
							component: {
								name: 'cl-upload'
							}
						},
						{
							prop: 'accountIds',
							label: '账号',
							value: [],
							component: {
								name: 'el-select',
								attrs: {
									placeholder: '请选择账号'
								},
								props: {
									multiple: true
								}
							},
							rules: {
								required: true,
								message: '账号不能为空'
							}
						},
						{
							prop: 'title',
							label: '商品标题',
							span: 24,
							component: {
								name: 'el-input',
								attrs: {
									size: 'mini'
								}
							}
						},
						{
							prop: 'url',
							props: {
								labelWidth: '0px'
							},
							component: {
								name: 'search-goods',
								methods: {
									input(e) {
										this.$emit('input', e);
									},
									Goodsinfo(e) {
										// console.log('zzzzzzz', e);
										self.enterGoodsInfo = e;
										app.setForm('tljMoney', e.preCommssion);
									}
								},
								render() {
									return (
										<searchCounpon
											onInput={this.input}
											onGoodsInfo={this.Goodsinfo}
											item={self.enterGoodsInfo}
											type={1}></searchCounpon>
									);
								}
							},
							rules: [{ required: true, message: '请先检索商品', trigger: 'blur' }]
						},
						{
							prop: 'tljMoney',
							label: '淘礼金金额：',
							component: {
								name: 'mdMoney_c',
								data() {
									return {
										value2: 0
									};
								},
								props: {
									value: null
								},
								watch: {
									value(val) {
										this.value2 = Number(val);
									}
								},

								methods: {
									Change(e) {
										this.$emit('input', e);
										if (self.appName != 'tjt') {
											if (
												this.value2 >=
												(self.enterGoodsInfo.endPrice -
													self.enterGoodsInfo.hzQuanOver) *
													0.8
											) {
												self.$message.error(
													'淘礼金金额不能大于商品券后价的80%'
												);
											}
										}
									}
								},

								render() {
									return (
										<div style="display:flex">
											<el-input-number
												max={
													Number(
														self.enterGoodsInfo.endPrice -
															self.enterGoodsInfo.hzQuanOver
													) || 0
												}
												step={0.01}
												precision={2}
												min={0}
												v-model={this.value2}
												onChange={this.Change}></el-input-number>
											<div style="margin-left:10px">
												到手价格￥
												<span style="color:red">
													{(
														parseFloat(
															self.enterGoodsInfo.endPrice || 0
														) -
														(this.value2 || 0) -
														(self.enterGoodsInfo.hzQuanOver || 0)
													).toFixed(2)}
												</span>
												元
											</div>
											<div style="margin-left:10px">
												佣金￥
												<span style="color:red">
													{self.enterGoodsInfo.preCommssion || 0}
												</span>
												元
											</div>
										</div>
									);
								}
							}
						},
						{
							prop: 'total',
							label: '活动商品个数：',
							value: parseInt(Math.random() * (10000 - 5000 + 1) + 5000, 10),
							component: {
								name: 'el-input-number',
								attrs: {
									'controls-position': 'right',
									min: 1,
									max: 10000
								},
								on: {
									change(val) {
										self.defNumMax = val;
									}
								}
							},
							rules: [
								{
									required: true,
									message: '请输入活动商品数量',
									trigger: 'blur'
								}
							]
						},
						{
							prop: 'time',
							label: '活动开始时间：',
							span: 12,
							value: moment().format('YYYY-MM-DD'),
							component: {
								name: 'el-date-picker',
								attrs: {
									type: 'date',
									'value-format': 'yyyy-MM-dd'
								}
							},
							rules: [
								{
									required: true,
									message: '请选择活动时间',
									trigger: 'blur'
								}
							]
						},
						{
							prop: 'startTime',
							props: {
								'label-width': '0px'
							},
							span: 12,
							component: {
								name: 'el-select',
								props: {
									placeholder: '请选择开始时间'
								},
								options: ''
							},
							rules: [
								{
									required: true,
									message: '请选择开始时间',
									trigger: 'blur'
								}
							]
						},
						{
							prop: 'time2',
							label: '活动结束时间：',
							span: 12,
							value: moment().format('YYYY-MM-DD'),
							component: {
								name: 'el-date-picker',
								attrs: {
									type: 'date',
									'value-format': 'yyyy-MM-dd'
								}
							},
							rules: [
								{
									required: true,
									message: '请选择活动时间',
									trigger: 'blur'
								}
							]
						},
						{
							prop: 'endTime',
							props: {
								'label-width': '0px'
							},
							span: 12,
							component: {
								name: 'el-select',
								props: {
									placeholder: '请选择结束时间'
								},
								options: ''
							},
							rules: [
								{
									required: true,
									message: '请选择结束时间',
									trigger: 'blur'
								}
							]
						},
						{
							prop: 'ysqLevel',
							label: '商品排序：',
							value: 100,
							component: {
								name: 'ysqlevels',
								data() {
									return {
										ysqLevel: 100
									};
								},
								props: {
									value: [String, Number]
								},
								mounted() {
									this.ysqLevel = this.value;
								},
								methods: {
									input(e) {
										this.$emit('input', e);
									}
								},
								render() {
									return (
										<div>
											<el-input-number
												v-model={this.ysqLevel}
												controls-position="right"
												onInput={this.input}
												min={1}
												max={10000}></el-input-number>
											<span style="color:#999999;margin-left:10px">
												序号越大，排序越靠前
											</span>
										</div>
									);
								}
							}
						},
						{
							prop: 'defNum',
							label: '预设抢购：',
							value: 0,
							component: {
								name: 'defNum-s',
								data() {
									return {
										value2: 0
									};
								},
								props: {
									value: [String, Number]
								},
								mounted() {
									this.value2 = this.value;
								},
								methods: {
									input(e) {
										this.$emit('input', e);
									}
								},
								render() {
									return (
										<div>
											<el-input-number
												v-model={this.value2}
												controls-position="right"
												onInput={this.input}
												min={0}
												max={self.defNumMax}></el-input-number>
										</div>
									);
								}
							}
						},
						{
							label: '状态',
							prop: 'status',
							value: 1,
							component: {
								name: 'el-select',
								options: [
									{
										label: '上架',
										value: 1
									},
									{
										label: '下架',
										value: 2
									}
								]
							}
						},
						{
							prop: 'appSort',
							label: '显示平台',
							value: [],
							component: {
								name: 'slelect-app',
								data() {
									return {
										list: [],
										checked: false
									};
								},
								props: {
									value: null
								},
								methods: {
									change(e) {
										this.$emit('input', e);
									},
									changeAll(type) {
										let all = [];
										self.formList.map(i => {
											all.push(i.value);
										});

										if (type) {
											this.list = all;
										} else {
											this.list = [];
										}
										this.$emit('input', this.list);
									}
								},
								render() {
									return (
										<div>
											<el-select
												clearable
												multiple
												style="width:100%"
												onChange={this.change}
												v-model={this.list}
												placeholder="请选择">
												{self.formList.map(e => {
													return (
														<el-option
															key={e.key}
															label={e.label}
															value={e.value}></el-option>
													);
												})}
											</el-select>
											<el-checkbox
												v-model={this.checked}
												onChange={this.changeAll}>
												全选平台
											</el-checkbox>
										</div>
									);
								}
							}
						}
					],
					op: {
						visible: true,
						layout: ['confirm']
					}
				})
				.set('layout', [
					[
						'refresh-btn',
						'add-btn',
						'slot-setTime',
						'query',
						'flex1',
						'slot-filter',
						'search-key'
					],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { next }) => {
					this.appName = stores.get('platForm') || '';
					let { list } = await next(params);
					list.map(item => {
						item.commissionRate = item.commissionRate + '%';
						item.sale = item.sale + '件';
					});
				})
				.on('delete', async (params, { next }) => {
					await next({
						...params[0]
					});
				})
				.on('submit', (isOpen, data, { next, done }) => {
					data.quanMLink = this.enterGoodsInfo.quanMLink; // 定金
					data.hzQuanOver = this.enterGoodsInfo.hzQuanOver; // 立减
					data.startTime = data.time + ' ' + data.startTime;
					data.endTime = data.time2 + ' ' + data.endTime;
					data.accountIds = data.accountIds.join(',');
					let applist = [];
					data.appSort.map(i => {
						applist.push({
							title: '',
							pick: '',
							level: '0',
							label: '',
							app: i
						});
					});
					data.appSort = applist;
					delete data.time;
					delete data.time2;
					let _sum = (
						0.01 *
						parseFloat(self.enterGoodsInfo.endPrice) *
						parseFloat(data.url.commissionRate)
					).toFixed(2);
					console.log(data);
					console.log(_sum);
					if (Number(data.tljMoney) >= Number(_sum)) {
						this.$confirm('淘礼金金额大于佣金，是否继续创建商品?', '提示', {
							type: 'warning',
							confirmButtonText: '确认',
							cancelButtonText: '取消'
						})
							.then(() => {
								next({
									...data,
									...data.url,
									type: 1,
									tljType: 1
								});
							})
							.catch(() => {
								done();
							});
					} else {
						next({
							...data,
							...data.url,
							type: 1,
							tljType: 1
						});
					}
				})
				.on('open', async isEdit => {
					let list = await this.$service.goodsMenagement.taobaoAccountTlj.userAccountList(
						{
							isBwbt: 1
						}
					);
					let timeList = await this.$service.goodsMenagement.goods.flashTime();
					let timeList2 = timeList.map(i => {
						return {
							value: i.time,
							label: i.time
						};
					});
					app.setData('upsert.items[prop:startTime].component.options', timeList2);
					app.setData('upsert.items[prop:endTime].component.options', timeList2);
					app.setData(
						'upsert.items[prop:accountIds].component.options',
						list.map(item => {
							return {
								label: item.accountName,
								value: item.accountId
							};
						})
					);

					this.defNumMax = 1;
					// 打开时清空商品数据
					this.enterGoodsInfo = {};
					this.getPlatform();
				})
				.done();

			app.refresh(this.params);
		},
		// 获取平台缓存
		getPlatform() {
			let data = stores.get('appPlatforms');
			if (data) {
				this.crud.setForm('appPlatforms', data);
			} else {
				this.crud.setForm('appPlatforms', [this.formList[0].value]);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	width: 100%;
	height: 100%;
}
.setsort {
	color: $color-link;
	cursor: pointer;
	margin: 5px 5px 5px 15px;
	:hover {
		opacity: 0.8;
	}
}
.nav {
	font-size: $font12;
	.nav-li {
		margin-left: 10px;
	}
}
.select {
	color: #409eff;
	display: inline-block;
	cursor: pointer;
	:hover {
		opacity: 0.8;
	}
}
.app-conf-list {
	display: flex;
	flex-wrap: wrap;
	margin: 0 -5px;

	li {
		width: calc(50% - 10px);
		list-style: none;
		margin: 0 5px 10px 5px;

		.el-input {
			margin-bottom: 5px;
		}
	}
}
</style>
